//
//  ForgetPassWordViewController.m
//  gpos_app
//
//  Created by 崔航飞 on 2018/8/18.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "ForgetPassWordViewController.h"
#import "Masonry.h"
#import "GPosAPI.h"
#import "WKProgressHUD.h"
#import "SVProgressHUD.h"
#import "XMRegisterViewController.h"
@interface ForgetPassWordViewController ()<UIGestureRecognizerDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UIView *backgroundViews;
@property (nonatomic,strong) UITextField *textField1;
@property (nonatomic,strong) UITextField *textField2;
@property (nonatomic,strong) UITextField *textField3;
@property (nonatomic,strong) UITextField *textField4;
@property (nonatomic,strong) UIButton *imgBtn3;
@property (nonatomic,strong) UIButton *imgBtn4;
@property (nonatomic,strong) UIButton *YZMBtn;
@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) UIImageView *BottomView;
@end

@implementation ForgetPassWordViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
    //去掉返回的文字
    self.navigationController.navigationBar.topItem.title = @"";
    self.navigationItem.title=@"忘记密码";
    
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=[UIColor whiteColor];
    [self initUI];
}
-(void)initUI{
    
    self.backgroundViews=[[UIView alloc] init];
    self.backgroundViews.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.backgroundViews];
    [self.backgroundViews mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).offset(kNavbarHeight);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.height.equalTo(@(KmainScreenHeiht - kNavbarHeight - kBottomSafeHeight));
        
    }];
    
    UIImageView *imgOne=[[UIImageView alloc] init];
    imgOne.image=[UIImage imageNamed:@"icon_shouji_l"];
    [self.backgroundViews addSubview:imgOne];
    [imgOne mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.top.equalTo(self.backgroundViews.mas_top).offset(30);
        
    }];
    
    
    UIView *line1=[[UIView alloc] init];
    line1.backgroundColor=[UIColor blueColor];
    [self.backgroundViews addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-32);
        make.top.equalTo(imgOne.mas_bottom).offset(6);
        make.height.equalTo(@(0.8));
        
    }];
    
    self.textField1=[[UITextField alloc] init];
    self.textField1.text=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];
    self.textField1.userInteractionEnabled=NO;
    self.textField1.placeholder=@"请输入手机号";
    [self.backgroundViews addSubview:self.textField1];
    [self.textField1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(imgOne.mas_right).offset(20);
        make.top.equalTo(self.backgroundViews.mas_top).offset(30);
        make.bottom.equalTo(line1.mas_top).offset(-6);
        make.width.equalTo(@(150));
    }];
    
    UIImageView *imgTwo=[[UIImageView alloc] init];
    imgTwo.image=[UIImage imageNamed:@"icon_yzm_l"];
    [self.backgroundViews addSubview:imgTwo];
    [imgTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.top.equalTo(line1).offset(30);
        
    }];
    
    
    UIView *line2=[[UIView alloc] init];
    line2.backgroundColor=[UIColor blueColor];
    [self.backgroundViews addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-32);
        make.top.equalTo(imgTwo.mas_bottom).offset(6);
        make.height.equalTo(@(0.8));
        
    }];
    
    self.textField2=[[UITextField alloc] init];
    self.textField2.placeholder=@"请输入验证码";
    self.textField2.keyboardType=UIKeyboardTypeNumberPad;
    [self.backgroundViews addSubview:self.textField2];
    [self.textField2 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(imgTwo.mas_right).offset(20);
        make.top.equalTo(line1.mas_top).offset(30);
        make.bottom.equalTo(line2.mas_top).offset(-6);
        make.width.equalTo(@(150));
    }];
    
    //验证码按钮
    self.YZMBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.YZMBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.YZMBtn addTarget:self action:@selector(YZMClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.YZMBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    self.YZMBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [self.backgroundViews addSubview:self.YZMBtn];
    
    [self.YZMBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(line1.mas_bottom).offset(30);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-35);
        make.width.equalTo(@(90));
        make.height.equalTo(@(22));
    }];
    
    
    UIImageView *imgThree=[[UIImageView alloc] init];
    imgThree.image=[UIImage imageNamed:@"icon_mima_l"];
    [self.backgroundViews addSubview:imgThree];
    [imgThree mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.top.equalTo(line2).offset(30);
        
    }];
    
    
    UIView *line3=[[UIView alloc] init];
    line3.backgroundColor=[UIColor blueColor];
    [self.backgroundViews addSubview:line3];
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-32);
        make.top.equalTo(imgThree.mas_bottom).offset(6);
        make.height.equalTo(@(0.8));
        
    }];
    
    self.textField3=[[UITextField alloc] init];
    self.textField3.placeholder=@"请输入6位交易密码";
    self.textField3.keyboardType=UIKeyboardTypeNumberPad;

    [self.backgroundViews addSubview:self.textField3];
    [self.textField3 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(imgThree.mas_right).offset(20);
        make.top.equalTo(line2.mas_top).offset(30);
        make.bottom.equalTo(line3.mas_top).offset(-6);
        make.width.equalTo(@(150));
    }];
    
    self.imgBtn3=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.imgBtn3 setImage:[UIImage imageNamed:@"icon_yangjingl"] forState:UIControlStateNormal];
    [self.imgBtn3 addTarget:self action:@selector(btn3Change:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundViews addSubview:self.imgBtn3];
    [self.imgBtn3 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(line2.mas_bottom).offset(25);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-38);
        
    }];
    
    
    self.imgBtn4=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.imgBtn4 setImage:[UIImage imageNamed:@"icon_yangjingl"] forState:UIControlStateNormal];
    [self.imgBtn4 addTarget:self action:@selector(btn4Change:) forControlEvents:UIControlEventTouchUpInside];
    [self.backgroundViews addSubview:self.imgBtn4];
    [self.imgBtn4 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(line3.mas_bottom).offset(25);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-38);
        
    }];
    
    
    UIImageView *imgFour=[[UIImageView alloc] init];
    imgFour.image=[UIImage imageNamed:@"icon_mima_l"];
    [self.backgroundViews addSubview:imgFour];
    [imgFour mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.top.equalTo(line3).offset(30);
        
    }];
    
    
    UIView *line4=[[UIView alloc] init];
    line4.backgroundColor=[UIColor blueColor];
    [self.backgroundViews addSubview:line4];
    [line4 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-32);
        make.top.equalTo(imgFour.mas_bottom).offset(6);
        make.height.equalTo(@(0.8));
        
    }];
    
    self.textField4=[[UITextField alloc] init];
    self.textField4.placeholder=@"请再次输入密码";
    self.textField4.keyboardType=UIKeyboardTypeNumberPad;

    [self.backgroundViews addSubview:self.textField4];
    [self.textField4 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(imgFour.mas_right).offset(20);
        make.top.equalTo(line3.mas_top).offset(30);
        make.bottom.equalTo(line4.mas_top).offset(-6);
        make.width.equalTo(@(150));
    }];
    
    self.textField1.delegate=self;
    self.textField2.delegate=self;
    self.textField3.delegate=self;
    self.textField4.delegate=self;
    //确认按钮
    self.BottomView =[[UIImageView alloc] init];
    self.BottomView.image=[UIImage imageNamed:@"icon_anniu_f"];
    self.BottomView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(QRBtns)];
    tap.delegate=self;
    [self.BottomView addGestureRecognizer:tap];
    [self.backgroundViews addSubview:self.BottomView];
    [self.BottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(line4.mas_bottom).offset(45);
        make.left.equalTo(self.backgroundViews.mas_left).offset(32);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-32);
        
    }];
    
    UILabel *backLab=[[UILabel alloc] init];
    backLab.text = @"确定";
    backLab.userInteractionEnabled =YES;
    backLab.textColor = [UIColor whiteColor];
    backLab.textAlignment = NSTextAlignmentCenter;
    [self.BottomView addSubview:backLab];
    [backLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.BottomView.mas_top).offset(25);
        make.left.equalTo(self.BottomView.mas_left);
        make.right.equalTo(self.BottomView.mas_right);
        make.height.equalTo(@(30));
    }];
    
}
-(void)QRBtns{
    
    if (self.textField2.text.length==0) {
        self.hud=[WKProgressHUD popMessage:@"验证码不能为空" inView:self.view duration:1 animated:YES];
    }else if (self.textField3.text.length==0){
        
        self.hud=[WKProgressHUD popMessage:@"交易密码不能为空" inView:self.view duration:1 animated:YES];
        
    }else if (self.textField4.text.length==0){
        
         self.hud=[WKProgressHUD popMessage:@"确认密码不能为空" inView:self.view duration:1 animated:YES];
        
    }else if (self.textField3.text.length<6){
        
        self.hud=[WKProgressHUD popMessage:@"交易密码必须为6位数字" inView:self.view duration:1 animated:YES];
        
    }else if (self.textField4.text.length<6){
        
         self.hud=[WKProgressHUD popMessage:@"确认密码必须为6位数字" inView:self.view duration:1 animated:YES];
        
    }
    else{//网络请求
        
        __weak typeof(self) weakSelf = self;
        /*
         参数1：phone
         参数2：verifyCode
         参数3：firstPassword
         参数4：secondPassword
         参数5：type
         */
        NSString *phone=[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:phone,@"phone",self.textField2.text,@"verifyCode",self.textField3.text,@"firstPassword",self.textField4.text,@"secondPassword",@(2),@"type", nil];
        [GPosAPI requestForgetJYPasswordloginPasswordWithParams:dic andCallback:^(id obj) {
            if (obj==nil)
            {
                
                [SVProgressHUD showErrorWithStatus:@"请求失败,请检查您的网络状态"];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else{
                
                if ([[obj objectForKey:@"code"] integerValue] ==200)
                {
//                    weakSelf.hud=[WKProgressHUD popMessage:@"修改成功" inView:self.view duration:1 animated:YES];
                    [SVProgressHUD showInfoWithStatus:@"修改成功"];
                    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                    
                }else if ([[obj objectForKey:@"code"] integerValue]==401 || [[obj objectForKey:@"code"] intValue] == 402){
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"NewLoginInView" object:nil];
                    UIStoryboard * mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    XMRegisterViewController *VC = [mainStory instantiateInitialViewController];
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                    VC.hidesBottomBarWhenPushed=YES;
                    //设置当前窗口的根控制器
                    [UIApplication sharedApplication].keyWindow.rootViewController=VC;
                    [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                    
                    
                }
                else{
                    
                    [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                    
                }
            }
        }];
        
        
    }
    
}
-(void)btn3Change:(UIButton *)btn{
    
    self.imgBtn3.selected = !self.imgBtn3.selected;
    
    if (self.imgBtn3.selected)
    {
        self.textField3.secureTextEntry = YES;
         [self.imgBtn3 setImage:[UIImage imageNamed:@"icon_biyan_l"] forState:UIControlStateNormal];
    }else{
        
        self.textField3.secureTextEntry = NO;
        [self.imgBtn3 setImage:[UIImage imageNamed:@"icon_yangjingl"] forState:UIControlStateNormal];
        
    }
    
}
-(void)btn4Change:(UIButton *)btn{
    
    self.imgBtn4.selected = !self.imgBtn4.selected;
    
    if (self.imgBtn4.selected)
    {
        self.textField4.secureTextEntry = YES;
        [self.imgBtn4 setImage:[UIImage imageNamed:@"icon_biyan_l"] forState:UIControlStateNormal];
    }else{
        
        self.textField4.secureTextEntry = NO;
        [self.imgBtn4 setImage:[UIImage imageNamed:@"icon_yangjingl"] forState:UIControlStateNormal];
        
    }
    
}
#pragma textFieldDelagate(限制输入的电话长度)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.textField3 ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.textField3.text.length >= 6) {
            self.textField3.text = [textField.text substringToIndex:6];
            
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        NSString *allstr=[textField.text stringByReplacingCharactersInRange:range withString:string];
        if (self.textField3.isSecureTextEntry ==YES)
        {
            self.textField3.text=allstr;
            return NO;
        }
    }
    
    if (textField == self.textField4 ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.textField4.text.length >= 6) {
            self.textField4.text = [textField.text substringToIndex:6];
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        NSString *allstr=[textField.text stringByReplacingCharactersInRange:range withString:string];
        if (self.textField4.isSecureTextEntry ==YES)
        {
            self.textField4.text=allstr;
            return NO;
        }
    }
    return YES;
}
//验证码的点击事件
-(void)YZMClick:(UIButton *)btn{
    
    //启动计时器
    [self setCountDown:btn];
    __weak typeof(self) weakSelf = self;
    /*
     参数1：phone
     
     参数5：type 2
     */
    NSString *type=@"2";
    NSString *phone=[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:phone,@"phone",type,@"type", nil];
    [GPosAPI requestSendCodeWithParams:dic andCallback:^(id obj) {
        if (obj==nil)
        {
            
            [SVProgressHUD showErrorWithStatus:@"请求失败,请检查您的网络状态"];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
            
        }else{
            
            if ([[obj objectForKey:@"code"] integerValue] ==200)
            {
                weakSelf.hud=[WKProgressHUD popMessage:@"验证码发送成功" inView:self.view duration:1 animated:YES];
                
            }else if ([[obj objectForKey:@"code"] integerValue]==401 || [[obj objectForKey:@"code"] intValue] == 402){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"NewLoginInView" object:nil];
                UIStoryboard * mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                XMRegisterViewController *VC = [mainStory instantiateInitialViewController];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                VC.hidesBottomBarWhenPushed=YES;
                //设置当前窗口的根控制器
                [UIApplication sharedApplication].keyWindow.rootViewController=VC;
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
                
            }
            else{
                
                [SVProgressHUD showErrorWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }
        }
    }];
    
}
//验证码按钮点击后，设置标题开始倒计时
-(void)setCountDown:(UIButton*)btn{
    
    __block int timeout=180; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t LHTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(LHTimer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(LHTimer, ^{
        
        if(timeout<=0){
            
            //倒计时结束，关闭
            dispatch_source_cancel(LHTimer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                [btn setTitle:@"重新发送" forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                btn.userInteractionEnabled = YES;
            });
        }else{
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示
                [btn setTitle:[NSString stringWithFormat:@"%@s",strTime] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                btn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(LHTimer);
    
}
@end
